import { login, logout } from "@/api/login";
import { getUserInfo } from "@/api/user";
import { notNull } from "@/utils";
import {
  UserInfoKey,
  getLocalStorage,
  getToken,
  removeLocalStorage,
  removeToken,
  setLocalStorage,
  setToken,
} from "@/utils/auth";
import { createStore } from "vuex";

export default createStore({
  state: {
    token: getToken(),
    userInfo: notNull(getLocalStorage(UserInfoKey))
      ? JSON.parse(getLocalStorage(UserInfoKey))
      : null,
  },
  getters: {},
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token;
    },
    SET_USER_INFO(state, userinfo) {
      state.userInfo = userinfo;
    },
  },
  actions: {
    Login({ commit }, loginForm) {
      return new Promise((resolve, reject) => {
        login(loginForm.username, loginForm.password)
          .then((res: any) => {
            setToken(res.token);
            commit("SET_TOKEN", res.token);
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout()
          .then((res) => {
            removeToken();
            removeLocalStorage(UserInfoKey);
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    GetUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getUserInfo()
          .then((res: any) => {
            setLocalStorage(UserInfoKey, JSON.stringify(res.user));
            commit("SET_USER_INFO", res.user);
            resolve(res.user);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
  },
  modules: {},
});
